package com.samehope.ar.controller;


import com.alibaba.fastjson.JSON;
import com.samehope.ar.common.CommonResult;
import com.samehope.ar.constant.QrCodeTypeEnum;
import com.samehope.ar.service.IDeviceService;
import com.samehope.ar.util.QRCodeUtils;
import com.samehope.ar.util.RedisUtil;
import com.samehope.ar.util.SessionUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 设备 前端控制器
 * </p>
 *
 * @author Zhang Luo
 * @since 2019-12-23
 */
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private IDeviceService deviceService;

    private final String BIND_PRE = "bqc";

    /**
     * 获取二维码
     * @param response
     */
    @PreAuthorize("hasRole('PROJECT')")
    @GetMapping("/bindQrCode")
    public void bindQrCode(HttpServletResponse response) {
        String code = RandomStringUtils.randomNumeric(4);
        String pattern = "{0}:{1}";
        String format = MessageFormat.format(pattern, BIND_PRE, SessionUtil.getCompanyId());
        RedisUtil.set(format, code, 60L);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            Map<String, Object> result = new HashMap<>();
            result.put("type", QrCodeTypeEnum.BIND.getCode());
            result.put("code", code);
            result.put("createBy", SessionUtil.getUserId().toString());
            BufferedImage image = QRCodeUtils.createImage(JSON.toJSONString(CommonResult.success(result)),
                    null, true);
            ImageIO.write(image, "png", outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有设备
     * @return
     */
    @PreAuthorize("hasRole('PROJECT')")
    @GetMapping("/devices")
    public CommonResult devices() {
        return CommonResult.success(deviceService.devices());
    }

    /**
     * 解绑设备
     * @param deviceId
     * @return
     */
    @PreAuthorize("hasRole('PROJECT')")
    @DeleteMapping("/unbind/{deviceId}")
    public CommonResult unbind(@PathVariable("deviceId") Long deviceId) {
        deviceService.unbind(deviceId);
        return CommonResult.success(null);
    }

}
